package com.test.springboot3.springboot3testdemo1.advice;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/8/2-下午2:23
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

  @ResponseBody
  @ExceptionHandler(value = {ConstraintViolationException.class})
  public ResponseEntity handleValidationException(ValidationException ex) {
    return new ResponseEntity(ex.getMessage(), HttpStatus.OK);
  }

  @ResponseBody
  @ExceptionHandler(value = {MethodArgumentNotValidException.class})
  public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
    BindingResult bindingResult = ex.getBindingResult();
    StringBuilder errorMsg = new StringBuilder("参数校验失败");
    bindingResult
        .getFieldErrors()
        .forEach(
            fieldError -> {
              errorMsg
                  .append(fieldError.getField())
                  .append(":")
                  .append(fieldError.getDefaultMessage())
                  .append(";");
            });
    return new ResponseEntity<>(errorMsg.toString(), HttpStatus.OK);
  }

  @ResponseBody
  @ExceptionHandler(value = {Exception.class})
  public ResponseEntity<?> handleException(HttpServletRequest request, Throwable ex) {
    return new ResponseEntity<>("global exception", HttpStatus.OK);
  }
}
